package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @Classname SimpleRedisLock
 * @Description 分布式锁
 * @Date 2022/5/25 14:25
 * @Created by 86182
 */
public class SimpleRedisLock implements ILock {


    private String name;
    private StringRedisTemplate stringRedisTemplate;

    private static final String KEY_PERFIX = "lock:";
    private static final String ID_PERFIX = UUID.randomUUID().toString(true) + "-";

    private static final DefaultRedisScript<Long> LUA_SCRIPT;

    static {
        LUA_SCRIPT = new DefaultRedisScript<>();
        LUA_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        LUA_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        //拿到当前线程id
        String threadId = ID_PERFIX + Thread.currentThread().getId();
        Boolean sucess = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PERFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(sucess);
    }

    @Override
    public void unlock() {
        stringRedisTemplate.execute(
                LUA_SCRIPT,
                Collections.singletonList(KEY_PERFIX + name),
                ID_PERFIX + Thread.currentThread().getId()
        );
    }


//    @Override
//    public void unlock() {
//        //拿到当前线程id
//        String threadId = ID_PERFIX + Thread.currentThread().getId();
//        String id = stringRedisTemplate.opsForValue().get(KEY_PERFIX + name);
//        if (threadId.equals(id)) {
//            stringRedisTemplate.delete(KEY_PERFIX + name);
//        }
//    }
}
